ngx.header["Server"] = "WS/0.4"

local token_id = ngx.req.get_headers()['token']
if token_id == nil then
	local resp = [[ {"status": 401, "msg": "fail", "data": "Unauthorized"} ]]
	ngx.header["Content-Type"] = "application/json"
	ngx.say(resp)
  return
end

local json = require 'cjson'
local res = ngx.location.capture(
  '/tokens/' .. token_id
)
if res.status ~= 200 then
  local resp = { status=5, msg='fail', data=res.body }
  ngx.header["Content-Type"] = "application/json"
  ngx.say(json.encode(resp))
  return
end

ngx.log(ngx.DEBUG, "token res:", res.status)
ngx.log(ngx.DEBUG, "token res body:", res.body)

local data = json.decode(res.body)
-- if data == nil then
	-- local resp = [[ {"status": 5, "msg": "fail", "data": "Token response error!"} ]]
	-- ngx.header["Content-Type"] = "application/json"
	-- ngx.say(resp)
  -- return
-- end

if data['status'] ~= 0 then
  local resp = { status=6, msg='fail', data=data['data']}
	ngx.header["Content-Type"] = "application/json"
	ngx.say(json.encode(resp))
  return
end

ngx.req.set_header('user_name', data['data']['user_name'])

ngx.exec('@api')
